import axios from 'axios';
import router from '../router'
import store from '../store'
import {Loading, Message, MessageBox } from 'element-ui'

const request = axios.create({
    baseURL : process.env.NODE_ENV === 'production' ? '/api' : '/api',
    withCredentials : true,
    headers : {
        'Content-Type': 'application/json;charset=UTF-8',
    }
})

let loadingInstance = null

// request interceptor
request.interceptors.request.use(
    config => {
        
        config.headers['authorization'] = store.state.userInfo.authorization ? store.state.userInfo.authorization : '';
        // if (config.params.showLoading == null) {
        //     loadingInstance = Loading.service({

        //     })
        // }
        
        return config;
    },
    error => {
        // do something with request error
        
        loadingInstance && loadingInstance.close()
        // console.log('request error', error)
        return Promise.reject(error)
    }
)

//response interceptor
request.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.code === 200 ){
            loadingInstance && loadingInstance.close();
            return res;
        } else if (res.code === 101) { //需要重新登录
            MessageBox({
                title : '提示',
                message : '請先登錄',
                callback : action => {
                    //清楚vuex中的用户信息
                    store.commit('setUserInfo', {
                        authorization : null,
                        avatar :null,//头像
                        nickname : null,//昵称
                        user_id : null,//用户id
                    })
                    router.replace('/login')
                }
            })
            loadingInstance && loadingInstance.close();
            return Promise.reject(res.msg)
        } else {
            Message({
                message : res.msg,
                type :'error'
            })
            loadingInstance && loadingInstance.close();
            return Promise.reject(res.msg)
        }
    },
    error =>{
        loadingInstance && loadingInstance.close()
        return Promise.reject(error)
    }
)

export default request;